﻿using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Assets.Scripts.Tool
{
    public class TabSelect:MonoBehaviour
    {
        private EventSystem eventSystem;

        void Start()
        {
            this.eventSystem=EventSystem.current;
        }
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.Tab))
            {
                Selectable next = null;
                if (eventSystem.currentSelectedGameObject != null)
                {
                    if (eventSystem.currentSelectedGameObject.activeInHierarchy)
                    {
                        var current = eventSystem.currentSelectedGameObject.GetComponent<Selectable>();
                        if (current != null)
                        {
                            if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
                            {
                                next = current.FindSelectableOnLeft();
                                if (next == null)
                                {
                                    next = current.FindSelectableOnUp();
                                }
                            }
                            else
                            {
                                next = current.FindSelectableOnRight();
                                if (next == null)
                                {
                                    next = current.FindSelectableOnDown();
                                }
                            }
                        }
                        else
                        {
                            if (Selectable.allSelectables.Count > 0)
                            {
                                next = Selectable.allSelectables[0];
                            }
                        }
                        if (next != null)
                        {
                            next.Select();
                        }
                    }
                }
            }
        }
    }
}